<template>
    <div class="chat-panel">
        <div class="chat-header">
            <span class="username">{{ user.nickname }}</span>
        </div>
        <div class="chat-messages">
            <el-scrollbar>
                <div v-for="message in props.messages" :key="message.timestamp" class="message-item" :class="{
                    'self-message-container': message.senderId === currentUserId
                }">
                    <div class="avatar-bubble">
                        <img :src="BaseUrl + user.avatar" v-if="message.senderId != currentUserId"
                            style="width: 40px; margin-right: 1vw; border-radius: 5px;">
                    </div>
                    <div class="message-bubble"
                        :class="message.senderId === currentUserId ? 'self-message' : 'other-message'">
                        {{ message.content }}
                    </div>
                    <div class="avatar-bubble">
                        <img :src="BaseUrl + userInfo.avatar" v-if="message.senderId == currentUserId"
                            style="width: 40px; margin-left: 1vw; border-radius: 5px;">
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <div class="chat-input">
            <el-input v-model="newMessage" placeholder="输入消息" @keyup.enter="sendMessageToFriend">
                <template #append>
                    <el-button type="primary" @click="sendMessageToFriend">发送</el-button>
                </template>
            </el-input>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { BaseUrl } from "../../../server/userApi";
import { getWebSocket, closeWebSocket } from "../../../server/websocket/websocket";
const currentUserId = computed(() => JSON.parse(localStorage.getItem("userInfo")).id);
const userInfo = JSON.parse(localStorage.getItem("userInfo"))



const props = defineProps({
    // 用户信息
    user: {
        type: Object,
        required: true,
    },
    // 对应用户的消息数组
    messages: {
        type: Array,
        required: true
    }

});

const emit = defineEmits(['send-message'])

// 响应式数据
const newMessage = ref("");

const socket = getWebSocket();  // 获取WebSocket实例


// 监听WebSocket消息
if (socket) {
    socket.onmessage = (event) => {
        console.log(event.data);
        const message = JSON.parse(event.data);

        props.messages.push({

            senderId: message.senderId,
            content: message.content,
            timestamp: new Date()
        });

    };
}

// 计算属性,拿到点击用户的id
const receiverId = computed(() => props.user.id);
// 发送消息到好友
const sendMessageToFriend = () => {
    if (newMessage.value.trim()) {
        const messageContent = newMessage.value;

        emit('send-message', newMessage.value)
        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify({ receiverId: receiverId.value, content: messageContent }));
        } else {
            console.error("WebSocket is not connected");
        }
        newMessage.value = "";
    }
};




// 函数定义
const fetchChatHistory = () => {
    // 这里应该是一个API调用来获取实际的聊天历史
    messages.value = [

    ];
};





// 生命周期钩子
onMounted(() => {

    // fetchChatHistory();
});

onUnmounted(() => {
    closeWebSocket();
});
</script>

<style lang="scss" scoped>
.chat-panel {
    display: flex;
    flex-direction: column;
    height: 100%;

    .chat-header {
        display: flex;
        align-items: center;
        padding: 10px;
        border-bottom: 1px solid #e6e6e6;

        .username {
            font-size: larger;
        }
    }

    .chat-messages {
        flex: 1;
        padding: 10px;
        overflow-y: auto;
        // background-color: aquamarine;
        background-image: url("chatbgk.jpg");
        background-size: cover;
        background-repeat: no-repeat;

        .message-item {
            display: flex;
            margin-bottom: 10px;

            &.self-message-container {
                justify-content: flex-end;
            }

            .message-bubble {
                max-width: 70%;
                padding: 10px 15px;
                border-radius: 4px;
                word-break: break-word;
                position: relative;
                margin-bottom: 10px;
                font-size: 16px;
                line-height: 1.4;
            }

            .self-message {
                background-color: #95ec69;
                color: #000;
                align-self: flex-end;
                // margin-right: 10px;
                margin-left: 40px;
            }

            .self-message::before {
                content: '';
                position: absolute;
                top: 14px;
                right: -10px;
                border-style: solid;
                border-width: 8px 0 8px 10px;
                border-color: transparent transparent transparent #95ec69;
            }

            .other-message {
                background-color: #bababa;
                color: #000;
                align-self: flex-start;
                margin-left: 10px;
                margin-right: 20px;
            }

            .other-message::before {
                content: '';
                position: absolute;
                top: 14px;
                left: -10px;
                border-style: solid;
                border-width: 8px 10px 8px 0;
                border-color: transparent #bababa transparent transparent;
            }


        }
    }

    .chat-input {
        padding: 10px;
        border-top: 1px solid #e6e6e6;
    }
}
</style>